#Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
#!/bin/bash

export ASCEND_SLOG_PRINT_TO_STDOUT=1
export ASCEND_GLOBAL_LOG_LEVEL=1

_CURR_PATH=$(cd $( dirname "$BASE_SOURCE[0]" ) && pwd)
ROOT_DEFAULT_PATH=/usr/local/Ascend/ascend-toolkit/latest
USER_DEFAULT_PATH=${ASCEND_HOME_PATH}
THREAD_NUM=""

function fn_log()
{
	log_level=$1
	log_lineno=$2
	log_content=$3
	log_time=`date "+%Y-%m-%d %H:%M:%S"`
	echo "[$log_time] [$log_level] [$log_lineno] $log_content"
	echo "[$log_time] [$log_level] [$log_lineno] $log_content"
}

function fn_source_env()
{
    if [ ! -f "${ROOT_DEFAULT_PATH}"/compiler/bin/setenv.bash ] && [ ! -f "${USER_DEFAULT_PATH}"/compiler/bin/setenv.bash ]; then
        fn_log "ERROR" $0:$LINENO "Compiler Setenv File Not Exists, Please Check."
        exit 1
    fi

    if [ ! -f "${ROOT_DEFAULT_PATH}"/runtime/bin/setenv.bash ] && [ ! -f "${USER_DEFAULT_PATH}"/runtime/bin/setenv.bash ]; then
        fn_log "ERROR" $0:$LINENO "Runtime Setenv File Not Exists, Please Check."
        exit 1
    fi

    if [ $(id -u) -ne 0 ]; then
        python_path=$(find ${HOME}/.local ${HOME}/Ascend -name "tbe" | grep python | grep site-packages)
        sitepackage=${python_path%/*}
        tbe_path="$_CURR_PATH""/../../tbe"
        export PYTHONPATH=$PYTHONPATH:${sitepackage}:${tbe_path}
        for type in "compiler" "runtime"; do
            source ${USER_DEFAULT_PATH}/${type}/bin/setenv.bash
            if [ "$?" != 0 ]; then
                fn_log "ERROR" $0:$LINENO "Source ${type} Env Failed."
                exit 1
            else
                fn_log "SUCCESS" $0:$LINENO "Source ${type} Env Successfully."
            fi
        done
        source ${USER_DEFAULT_PATH}/bin/setenv.bash
        if [ "$?" != 0 ]; then
            fn_log "ERROR" $0:$LINENO "Source Env Failed."
            exit 1
        else
            fn_log "SUCCESS" $0:$LINENO "Source Env Successfully."
        fi
    else
        for type in "compiler" "runtime"; do
            source ${ROOT_DEFAULT_PATH}/${type}/bin/setenv.bash
            if [ "$?" != 0 ]; then
                fn_log "ERROR" $0:$LINENO "Source ${type} Env Failed."
                exit 1
            else
                fn_log "SUCCESS" $0:$LINENO "Source ${type} Env Successfully."
            fi
        done
        source ${ROOT_DEFAULT_PATH}/bin/setenv.bash
        if [ "$?" != 0 ]; then
            fn_log "ERROR" $0:$LINENO "Source Env Failed."
            exit 1
        else
            fn_log "SUCCESS" $0:$LINENO "Source Env Successfully."
        fi
    fi
}

export_ccache_compilercheck() {
    CCEC_PATH=$(which ccec)
    CCEC_SHA256SUM=$(sha256sum "${CCEC_PATH}" | cut -d" " -f1)

    export CCACHE_COMPILERCHECK="string:${CCEC_SHA256SUM}"
}

# gen ccec
gen_ccec() {
    CCEC_PATH=$(which ccec)
    $(> ccec)
    echo "#!/bin/bash" >> ccec
    echo "ccache_args=""\"""${CCACHE_ARGS} ${CCEC_PATH}""\"" >> ccec
    echo "args=""$""@" >> ccec
    echo "echo ""\"""$""{ccache_args} ""$""args""\"" >> ccec
    echo "eval ""\"""$""{ccache_args} ""$""args""\"" >> ccec
    chmod +x ccec
}

function fn_generate_opc_info()
{
    short_soc_version=$1
    echo "**************Start to Generate Opc Info*****************"
    csv_file="opc_info_${short_soc_version}.csv"
    bash gen_opcinfo_for_socversion.sh ${short_soc_version} ${csv_file}
    if [ "$?" != 0 ]; then
        fn_log "ERROR" $0:$LINENO "Gen opc info failed, Please Check!"
        exit 1
    else
        fn_log "SUCCESS" $0:$LINENO "Generate Opc Info Successfully"
    fi
    echo "**************End to Generate Opc Info*****************"
}

function fn_generate_single_op()
{
    OUTPUT_PATH=$1
    short_soc_version=$2
    echo "**************Start to Generate Single Op*****************"
    # gen compile task
    task_path="build_binary_all"
    [ -d "./${task_path}/" ] || mkdir -p ./${task_path}/
    rm -f ./${task_path}/*

    binary_csv_file="$_CURR_PATH/../binary_config/binary_config.csv"
    dos2unix "${binary_csv_file}"
    if [ "${index}" = "" ]; then
        op_list=$(cat ${binary_csv_file} | tail -n +3 | awk -F, '{print $1}')
    else
        op_list=$(cat ${binary_csv_file} | grep ",${index}$" | awk -F, '{print $1}')
    fi

    op_list=($3)
    if [ "${op_list}" != "" ]; then
        for op_type in ${op_list}; do
            bash build_binary_single_op_gen_task.sh ${op_type} ${short_soc_version} ${OUTPUT_PATH} ${task_path} ${csv_file}
        done
        # exe task
        bash build_binary_single_op_exe_task.sh ${task_path} ${THREAD_NUM}
    fi
}

function fn_main()
{
    cd $CANNDEV_DIR/ops/built-in/kernel/binary_script
    while true
    do
        #Set Optional Args
        case "$1" in
        --ccache_args=*)
            CCACHE_ARGS=$(echo ${1} | cut -d"=" -f2)
            shift
            ;;
        --index=*)
            GROUP_INDEX=$(echo ${1} | cut -d"=" -f2)
            shift
            ;;
        --thread_num=*)
            THREAD_NUM=$(echo ${1} | cut -d"=" -f2)
            fn_log "INFO" $0:$LINENO "set thread num = ${THREAD_NUM}"
            shift
            ;;
        -*)
            fn_log "ERROR" $0:$LINENO "ERR_NO:${PARAM_INVALID};ERR_DES:Unsupported parameters [$1], operation execute failed"
            exit 1
            ;;
        *)
            break
            ;;
        esac
    done

    #设置并行编译数，当前默认16个进程进行算子编译，即同时16个算子进行二进制编译
    if [ "${THREAD_NUM}" = "" ]; then
        THREAD_NUM=16
    fi

    #Get working group
    sum_group=$(echo ${GROUP_INDEX} | cut -d"-" -f1)
    index=$(echo ${GROUP_INDEX} | cut -d"-" -f2)

    if [ $# -lt 3 ]; then
        fn_log "ERROR" $0:$LINENO "Input Args Nums Not Equal Three, Please Check The Num."
        fn_log "INFO" $0:$LINENO "bash build_binary_bisheng.sh {OUTPUT_PATH} {SHORT_SOC_VERSION} {OPS_NAME}"
        exit 1
    fi

    OUTPUT_PATH=$1
    SHORT_SOC_VERSION=$2
    short_soc_version="$(echo ${SHORT_SOC_VERSION} | tr 'a' 'A')"

    fn_source_env
    export_ccache_compilercheck
    if [ "${CCACHE_ARGS}" != "" ]; then
        gen_ccec
    fi
    export PATH=${_CURR_PATH}:$PATH
    fn_generate_opc_info $short_soc_version
    fn_generate_single_op $OUTPUT_PATH $short_soc_version $3
    fn_log "INFO" $0:$LINENO "run bscpp_op_build_bisheng.sh SUCCESS"
}

fn_main "$@"